#include "PlayerPlane.h"
#include "MainScene.h"
#include "Bullet.h"
#include "config.h"
#include <QDebug>
#define BULLET_MAX_NUM 10

PlayerPlane::PlayerPlane(MainScene* mainScene, QWidget *parent)
    : BasePlane(parent),
    m_mainScene(mainScene),      // 必须初始化场景指针
    m_moveDirection(0),
    m_speed(6),
    m_fireCoolDown(5),
    m_fireCoolDownCounter(0)
{
    Q_ASSERT_X(m_mainScene, "PlayerPlane", "MainScene指针不能为空");
    setPixmap(QPixmap(HERO_PATH));
}

void PlayerPlane::setMoveDirection(int direction)
{
    // 位或操作添加方向（保留原有方向）
    m_moveDirection |= direction;
}

void PlayerPlane::clearMoveDirection(int direction)
{
    // 位与非操作清除方向（不影响其他方向）
    m_moveDirection &= ~direction;
}

void PlayerPlane::fire()
{
    // 防御性编程：检查指针和数组有效性
    if (!m_mainScene) {
        qCritical() ;
        return;
    }

    if (m_fireCoolDownCounter > 0) {
        return; // 冷却中不发射
    }

    // 创建新子弹（玩家子弹）
    Bullet bullet;
    bullet.SetPlayerBullet(true);

    // 计算发射位置（飞机中心上方）
    const int bulletX = x() + width()/2 - bullet.width/2;
    const int bulletY = y() - bullet.height;
    bullet.setPosition(bulletX, bulletY);

    // 在主场景的子弹数组中寻找空闲位置
    for (int i = 0; i < BULLET_MAX_NUM; ++i) {
        if (m_mainScene->addBullet(i).isFree()) {
            m_mainScene->addBullet(i, bullet);
            m_fireCoolDownCounter = m_fireCoolDown; // 重置冷却
            break;
        }
    }
}

void PlayerPlane::updatePosition()
{
    // 更新冷却计数器
    if (m_fireCoolDownCounter > 0) {
        --m_fireCoolDownCounter;
    }

    // 计算新位置
    int newX = x();
    int newY = y();

    if (m_moveDirection & Up)    newY -= m_speed;
    if (m_moveDirection & Down)  newY += m_speed;
    if (m_moveDirection & Left)  newX -= m_speed;
    if (m_moveDirection & Right) newX += m_speed;

    // 边界约束
    newX = qBound(0, newX, parentWidget()->width() - width());
    newY = qBound(0, newY, parentWidget()->height() - height());

    // 应用新位置
    move(newX, newY);
}
